
from sqlalchemy import text

from tool_utils import get_sql_lite_tool

import streamlit as st

import data_source_manage_page
import single_table_import_page
import all_database_import_page
import single_table_metadata_manage
import database_table_relationship_mange


def init_sqlite_database() :
    """初始化数据库，执行SQL脚本"""
    try:
        # 读取SQL文件
        with open('./sql/init.sql', 'r', encoding='utf-8') as f:
            sql_script = f.read()

        sql_lite_tool = get_sql_lite_tool()

        try:
            # 分割SQL语句并执行
            statements = sql_script.split(';')
            with sql_lite_tool.engine.connect() as conn:
                for statement in statements:
                    if statement.strip():
                        conn.execute(text(statement))
                conn.commit()

            
        except Exception as e:
            conn.rollback()
            st.error(f"数据库初始化失败: {str(e)}")
        finally:
            conn.close()

    except FileNotFoundError:
        st.error("初始化SQL文件未找到！")
    except Exception as e:
        st.error(f"初始化数据库时发生错误: {str(e)}")



    




def main():

    main_page()
    init_sqlite_database()

    if st.session_state.current_page == "数据源管理":
        data_source_manage_page.data_sources_management_page(st)
    elif st.session_state.current_page == "快速导入":
        single_table_import_page.single_table_import_page(st)
    elif st.session_state.current_page == "整库导入":
        all_database_import_page.all_database_import(st)
    elif st.session_state.current_page == "元数据管理":
        single_table_metadata_manage.single_table_metadata_manage(st)
    elif st.session_state.current_page == "表关系管理":
        database_table_relationship_mange.database_table_relationship_mange(st)
    elif st.session_state.current_page == "test":
        database_table_relationship_mange.newnew(st)




def main_page():
    # 页面布局
    st.set_page_config(page_title="数据源管理系统", layout="wide")

    # 初始化会话状态
    if "current_page" not in st.session_state:
        st.session_state.current_page = "数据源管理"
    if "edit_source" not in st.session_state:
        st.session_state.edit_source = None

    # 侧边栏菜单
    with st.sidebar:
        st.header("导航菜单")
        menu_option = st.radio(
            "选择功能",
            ["数据源管理", "快速导入", '整库导入','元数据管理','表关系管理','test'],
            index=0 if st.session_state.current_page == "数据源管理" else 1
        )
        st.session_state.current_page = menu_option




if __name__ == "__main__":

    main()